package it.francescogabbrielli.android.solidalapp.actions;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import it.francescogabbrielli.android.solidalapp.Action;
import it.francescogabbrielli.android.solidalapp.Constants;
import it.francescogabbrielli.android.solidalapp.EndpointsUtils;
import it.francescogabbrielli.android.solidalapp.R;
import it.francescogabbrielli.android.solidalapp.SolidalApp;
import it.francescogabbrielli.android.solidalapp.SolidalApp.DataKey;
import it.francescogabbrielli.android.solidalapp.responseendpoint.Responseendpoint;
import it.francescogabbrielli.android.solidalapp.responseendpoint.model.Response;

/**
 * Update is used only to send a feedback to a response
 */
public class EndpointsUpdateResponse extends Action {
	
	private Response response;

	@Override
	public void execute() throws Exception {
		
		// the feedback is implicitly set by the bundle passed in here
		Response temp = getModel(Response.class);
		
		int feedback = intent.getIntExtra(Constants.FEEDBACK, 0);
		if (feedback!=0 && !temp.getCompleted()) {
			Responseendpoint endpoint = EndpointsUtils.buildEndpoint(Responseendpoint.class);
			response = endpoint.updateResponse(temp).execute();
			setModel(response);
		}
	
	}

	@Override
	public void onPostExecute() throws Exception {
		if (response!=null) {
			
			Log.d(getAction(), "Feedback sent: "+response);
				
			SharedPreferences prefs = context.getSharedPreferences(
					SolidalApp.class.getCanonicalName(), Context.MODE_PRIVATE);
			synchronized (prefs) {
				prefs.edit().putBoolean(Constants.FORCE_LOADER+Constants.LOADER_REQUEST, true)
					.commit();
			}
			
			app.setData(DataKey.FILE_RESPONSE, response);
			app.alert(R.string.file_feedback_sent_message);
			
		} else
			Log.w(getAction(), "Feedback already sent?");
	}

}
